package com.quanyan.user.web.filter;

import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.user.AppUserCacheInfo;
import com.quanyan.common.utils.HttpServletRequestWrapper;
import com.quanyan.common.utils.MD5Utils;
import com.quanyan.redisCluster.config.RedisTemplate;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.user.service.UserInformationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;


/**
 * @Author Hugo.Wwg
 * @Since 2016-06-02
 */
@Component
public class CommonFilter implements Filter {

    private final static Logger logger = LoggerFactory.getLogger(CommonFilter.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserInformationService userInformationService;

    public static String getBodyString(BufferedReader br, String reqUrl) {
        String inputLine;
        StringBuilder sb = new StringBuilder();
        try {
            while ((inputLine = br.readLine()) != null) {
                sb.append(inputLine);
            }
            br.close();
        } catch (IOException e) {
            logger.warn("requestUrl: " + reqUrl + ", Request error: "
                    + e.getMessage() + "Request URI: ");
        }
        return sb.toString();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    private void ajaxError(ApiResponseEnum apiResponseEnum, ServletResponse response)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSON(APIResponse.returnFail(apiResponseEnum)).toString());
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        Long startTime = System.currentTimeMillis();
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String uri = request.getRequestURI().replaceAll("//","/");
        String sign = request.getHeader("sign");
        String appChannel = request.getHeader("appChannel");
//        //判断接口路径，开发中的接口返回404
        if(uri.startsWith("/api/user/base/getServerStatus")) {
            File file = new File("/opt/user/status.txt");
            if (file.exists()) {
                response.setStatus(200);
            } else {
                response.setStatus(404);
            }
            return;
        }

        String userCookiesName = request.getHeader("userCookiesName");
        logger.info("uri:"+uri+";sign:"+sign+";userCookiesName:"+userCookiesName+";appChannel:"+appChannel);
        ServletRequest requestWrapper = new HttpServletRequestWrapper(request);
        String reqData = getBodyString(requestWrapper.getReader(), uri);
        logger.warn("CommonFilter读取body中的参数: " + reqData);
        if(uri.startsWith("/api/user/c/")
                || uri.startsWith("/admin/api/user/")
                || uri.startsWith("/api/user/base/")
                || uri.startsWith("/user/base/checkVersion")
                || uri.startsWith("/api/user/interest/list")
                || uri.startsWith("/api/user/assets/userCouponList")
                || uri.startsWith("/api/user/assets/userAccumulateList")
                || uri.startsWith("/api/user/customerService")
                || uri.startsWith("/api/user/login/validCode")
                || uri.startsWith("/api/user/login/appInit")
                || uri.startsWith("/api/user/login/validateMobile")
                || uri.startsWith("/api/user/login/getUser")
                || uri.startsWith("/api/user/dynamic/getFirstNewsList")
                || uri.startsWith("/api/user/dynamic/list")
                || uri.startsWith("/api/user/dynamic/loadComment")
                || uri.startsWith("/api/user/dynamic/getForwardTopicList")
                || uri.startsWith("/api/user/dynamic/dynamicDetail")
                || uri.startsWith("/api/user/praise/loadPraise")
                || uri.startsWith("/api/user/dynamic/getFirstPageMans")
                || uri.startsWith("/api/user/dynamic/homePage")
                || uri.startsWith("/api/user/dynamic/topicDetail")
                || uri.startsWith("/api/user/dynamic/index")
                || uri.startsWith("/api/user/discoveryVideo/")
                || uri.startsWith("/api/user/information/randomGenerateLables")
                || uri.startsWith("/api/user/information/getUserIndex")
                || uri.startsWith("/api/user/information/updateUserRedis")
                ){

        }else{

            RedisKey redisKey = new RedisKey(userCookiesName, "");
            AppUserCacheInfo appUserCacheInfo = (AppUserCacheInfo)redisTemplate.getObjectFromC(redisKey, AppUserCacheInfo.class);

            String md5Sign = MD5Utils.MD5Encode(reqData + Constants.SECRET_KEY);
            if (sign == null || !sign.equals(md5Sign)) {
                ajaxError(ApiResponseEnum.ILLEGAL_PROTOCOL, response);
                return;
            }

            if (appUserCacheInfo == null) {
                ajaxError(ApiResponseEnum.COOKIES_IS_NULL, response);
                return;
            }else{
                Integer uid = appUserCacheInfo.getUser_id();
                String dsn = appUserCacheInfo.getDsn();
                if (uid != null && !uid.equals(0) ) {
                    request.setAttribute("uid", uid);
                    request.setAttribute("dsn",dsn);
                    request.setAttribute("userCookiesName",userCookiesName);
                    request.setAttribute("appChannel",appChannel);
                    request.setAttribute("cookies",appUserCacheInfo);
                    request.setAttribute("dev", appUserCacheInfo.getDev());
                    boolean isEnable = userInformationService.isUserEnable(uid);    //判断用户账号是否可用
                    if (!isEnable && !uri.startsWith("/api/user/login/login")) {
                        ajaxError(ApiResponseEnum.NEED_USER_LOGIN, response);
                        return;
                    }
                }else if(uid != null && uid.equals(0) && (uri.startsWith("/api/user/interest") ||
                                           uri.startsWith("/api/user/information/my") ||
                                           uri.startsWith("/api/user/information/index") ||
                                           uri.startsWith("/api/user/login") ||
                        uri.startsWith("/api/user/download/channel") ||
                                            uri.startsWith("/api/user/banner/getBannerInfo"))
                                                        ){
                    request.setAttribute("uid", null);
                    request.setAttribute("dsn",dsn);
                    request.setAttribute("userCookiesName",userCookiesName);
                    request.setAttribute("appChannel",appChannel);
                    request.setAttribute("cookies",appUserCacheInfo);
                    request.setAttribute("dev", appUserCacheInfo.getDev());
                }else{
                    ajaxError(ApiResponseEnum.NEED_USER_LOGIN, response);
                    return;
                }
            }

        }
        if (uri.startsWith("/api/user/push/readAndPraise")) {
            response.setHeader("Access-Control-Allow-Origin", "*");
        }
        chain.doFilter(requestWrapper, response);

        logger.info("接口【"+uri+"】执行时间为："+ (System.currentTimeMillis() - startTime) + "毫秒");
    }

    @Override
    public void destroy() {

    }
}
